import { Button, Form, Input, message } from "antd";
import "./index.scss";
import { login } from "../../api/user";
import { useNavigate } from "react-router-dom";

interface LoginUser {
  username: string;
  password: string;
}

const layout1 = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
};

const layout2 = {
  labelCol: { span: 0 },
  wrapperCol: { span: 24 },
};

export const Login = () => {
  const navigate = useNavigate();

  const onFinish = async (values: LoginUser) => {
    const res = await login(values.username, values.password).catch((error) => {
      return Promise.resolve({
        token: null,
        user: null,
        message: error.response?.data?.message || "系统繁忙，请稍后再试",
      });
    });
    console.log(res);
    if (res.token) {
      message.success("登录成功");

      localStorage.setItem("token", res.token);
      localStorage.setItem("userInfo", JSON.stringify(res.user));

      navigate("/");
    } else {
      message.error(res.message);
    }
  };
  return (
    <div id="login-container">
      <div className="left-section">
        <div className="brand">
          <h2>聊天室</h2>
          <p>随时随地，与好友保持联系</p>
        </div>
      </div>
      <div className="login-form">
        <h1>欢迎回来</h1>
        <Form {...layout1} onFinish={onFinish} colon={false} autoComplete="off">
          <Form.Item
            label="用户名"
            name="username"
            rules={[{ required: true, message: "请输入用户名!" }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, message: "请输入密码!" }]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item {...layout2}>
            <div className="links">
              <a href="/register">创建账号</a>
              <a href="/update-password">忘记密码</a>
            </div>
          </Form.Item>

          <Form.Item {...layout2}>
            <Button className="btn" type="primary" htmlType="submit">
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};
